package com.wangyadong.hobby.thread.io;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2019/7/114:37
 **/
public class TCPServer implements Cloneable, Runnable {

    Thread runner = null;
    ServerSocket server = null;
    Socket data = null;
    private boolean done = false;

    public synchronized void startServer(int port) throws IOException {
        if (runner == null) {
            server = new ServerSocket(port);
            runner = new Thread(this);
            runner.start();
        }
    }

    public synchronized void stopServer()
    {
        this.runner.interrupt();
        this.done = true;
    }

    public synchronized boolean getDone() {
        return this.done;
    }

    @Override
    public void run() {
        if (server != null) {
            while (!getDone()) {
                try {
                    Socket dataSocket = server.accept();
                    TCPServer newScokert = (TCPServer) clone();
                    newScokert.server = null;
                    newScokert.data = dataSocket;
                    newScokert.runner = new Thread(newScokert);
                    newScokert.runner.start();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (CloneNotSupportedException e) {
                    e.printStackTrace();
                }
            }
        } else {
            run(data);
        }
    }

    public void run(Socket data) {
        try {
            DataOutputStream dos = new DataOutputStream(data.getOutputStream());
            dos.writeByte(TypeServerConstants.WELCOME);
            DataInputStream dis = new DataInputStream(data.getInputStream());
            while (true) {
                byte b = dis.readByte();
                if (b != TypeServerConstants.GET_STRING_REQUEST) {
                    System.out.println("Client sent unkonw request");
                    continue;
                }
                dos.writeByte(TypeServerConstants.GET_STRING_RESPONSE);
                dos.writeUTF("This is a test string");
                dos.flush();
            }
        } catch (IOException e) {
            System.out.println("Client terminating:" + e);
            return;
        }
    }

    public static void main(String[] args) throws IOException {
        TCPServer tcpServer = new TCPServer();
        tcpServer.startServer(Integer.valueOf(args[0]));
        System.out.println("Server ready and waiting...");
    }
}
